package com.sec.bnjey.activity;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.Camera;
import android.graphics.Matrix;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.Transformation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.sec.bnjey.BaseActivity;
import com.sec.bnjey.R;
import com.sec.bnjey.activity.dialog.IKPopup;
import com.sec.bnjey.activity.dialog.IKPopup.Builder.onIKPopupClickListener;
import com.sec.bnjey.activity.dialog.RbDialog;
import com.sec.bnjey.adapter.MileageHistoryAdapter;
import com.sec.bnjey.bluetooth.BtService;
import com.sec.bnjey.bluetooth.BtUtil;
import com.sec.bnjey.bluetooth.OBDListener;
import com.sec.bnjey.database.OBDDbHelper;
import com.sec.bnjey.network.NetworkEventListener;
import com.sec.bnjey.utils.RbLog;
import com.sec.bnjey.vo.DriveDetailEntity;

public class NewMileageActivity extends BaseActivity implements
		OnClickListener, NetworkEventListener, OBDListener {

	private static final String TAG = "NewMileageActivity";

	private TextView tv_starttimeText, text_mileage00;
	private boolean mRealtimeDriveIsValid = false;
	MileageHistoryAdapter mMileageHistoryAdapter;

	public class DriveHistoryEntity {

		public DriveHistoryEntity(int startTimeVtalk) {

			this.startTime = startTimeVtalk;
			Calendar startTimeCalendar = utilGetCalendar(startTimeVtalk);
			this.title = String.valueOf(startTimeCalendar.get(Calendar.YEAR))
					+ "년 "
					+ String.valueOf(startTimeCalendar.get(Calendar.MONTH) + 1)
					+ "월 "
					+ String.valueOf(startTimeCalendar.get(Calendar.DATE))
					+ "일 "
					+ String.valueOf(startTimeCalendar
							.get(Calendar.HOUR_OF_DAY))
					+ "시 "
					+ String.valueOf(startTimeCalendar.get(Calendar.MINUTE)
							+ "분 ");

			RbLog.d(TAG, this.title);
		}

		public DriveHistoryEntity() {
			// TODO Auto-generated constructor stub
		}

		public String title;
		public int startTime;
		public int endTime;
		public int count;

	}

	DriveDetailEntity mDriveDetailResultEntity;
	ArrayList<DriveDetailEntity> mDriveDetailArrayList;

	private Button B_TopMenu_Left, bt_realtime, bt_run, bt_day, bt_month;
	private ToggleButton tb_hud;
	private TextView TV_TopMenu_Title;
	private ImageView IV_TopMenu_OBD, IV_TopMenu_Bluetooth, IV_TopMenu_Alert;

	// view mode, tab
	private final int TAB_REALTIME = 0;
	private final int TAB_RUN = 1;
	private final int TAB_DAY = 2;
	private final int TAB_MONTH = 3;

	int mSelectTab = TAB_REALTIME;
	boolean mIsListView = true;

	ArrayList<DriveHistoryEntity> mDriveHistoryArrayList = new ArrayList<DriveHistoryEntity>();
	ArrayList<DriveHistoryEntity> temp_mDriveHistoryArrayList = new ArrayList<DriveHistoryEntity>();

	byte[] data = new byte[66];
	byte[] b = new byte[16];
	byte[] index = { 0x00, 0x00 };
	byte[] d = new byte[64];
	byte[] xx = new byte[64];

	byte[] raw = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09,
			0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F };// ��ȣȭŰ
	int index_int = 0;

	ProgressDialog pd;
	String FIRST_TIME;

	byte[] mRealTimeSpeed = new byte[2];// pid
	byte[] mRealTimeCool = new byte[2];// pid
	byte[] mRealTimeVolt = new byte[2];

	int data0 = 0;
	int data1 = 0;
	int data2 = 0;
	byte data3 = 0x01;
	float data4 = 0;
	byte data5 = 0x01;
	float data6 = 0;
	byte data7 = 0x01;
	float data8 = 0;

	int second = 0;
	int minute = 0;
	int cigan = 0;
	int day = 0;
	int month = 0;
	int mValue = 0;

	Calendar cal = Calendar.getInstance();
	Calendar cal2 = Calendar.getInstance();

	private RelativeLayout rl_realtime;
	private LinearLayout ll_detaildata;
	private ListView lv_history;

	int mDriveDetailStartTime;

	private int mRealtimeDriveDistance;
	private int mRealtimeDriveDistanceCheckCnt;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.newmileageactivity);

		RbLog.d(TAG, "onCreate");

		mRealtimeDriveDistance = 0;
		mRealtimeDriveDistanceCheckCnt = 0;

		mDriveDetailResultEntity = new DriveDetailEntity();
		mDriveDetailArrayList = new ArrayList<DriveDetailEntity>();

		viewInit();
		updateTopMenuIcons();

		if (BtService.getBtService().isOBDDeviceConnected())
			viewSelectTab(TAB_REALTIME, true);
		else
			viewSelectTab(TAB_RUN, true);

	}

	private void viewSelectTab(int newTab, boolean force) {

		if (force == false) {
			if (mSelectTab == newTab && mIsListView == true)
				return;
		}

		mSelectTab = newTab;
		mIsListView = true;

		mDriveHistoryArrayList.clear();
		mDriveDetailResultEntity.reset();
		lv_history.setAdapter(null);
		viewUpdate(mSelectTab);
		getMileageData(mSelectTab);
	}

	@Override
	protected void onPause() {
		super.onPause();
		mSelectTab = -1;
	}

	private byte[] checkOBDStatus() {

		byte[] data = BtService.getBtService().OBD_CommunicationStart();

		RbLog.d(TAG, "checkOBDStatus " + data);
		return data;
	}

	private void viewInit() {

		// init top menu
		B_TopMenu_Left = (Button) findViewById(R.id.B_TopMenu_Left);
		B_TopMenu_Left.setOnClickListener(this);
		TV_TopMenu_Title = (TextView) findViewById(R.id.TV_TopMenu_Title);
		IV_TopMenu_Alert = (ImageView) findViewById(R.id.IV_TopMenu_Alert);
		IV_TopMenu_Bluetooth = (ImageView) findViewById(R.id.IV_TopMenu_Bluetooth);
		IV_TopMenu_OBD = (ImageView) findViewById(R.id.IV_TopMenu_OBD);

		// init mid data
		rl_realtime = (RelativeLayout) findViewById(R.id.rl_realtime);
		lv_history = (ListView) findViewById(R.id.lv_history);
		ll_detaildata = (LinearLayout) findViewById(R.id.ll_detaildata);
		tv_starttimeText = (TextView) findViewById(R.id.text_mileage0);
		text_mileage00 = (TextView) findViewById(R.id.text_mileage00);

		mMileageHistoryAdapter = new MileageHistoryAdapter(
				getApplicationContext(), R.layout.mileage_list,
				mDriveHistoryArrayList);
		bt_realtime = (Button) findViewById(R.id.bt_realtime);
		bt_run = (Button) findViewById(R.id.bt_run);
		bt_day = (Button) findViewById(R.id.bt_day);
		bt_month = (Button) findViewById(R.id.bt_month);
		tb_hud = (ToggleButton) findViewById(R.id.tb_hud);
		bt_realtime.setOnClickListener(this);
		bt_run.setOnClickListener(this);
		bt_day.setOnClickListener(this);
		bt_month.setOnClickListener(this);
		tb_hud.setOnClickListener(this);
	}

	private void viewUpdate(int viewmode) {

		RbLog.d(TAG, "viewUpdate " + viewmode);
		switch (viewmode) {

		case TAB_REALTIME:
			TV_TopMenu_Title.setText(R.string.top_menu_title_mileage);
			rl_realtime.setAnimation(null);
			tb_hud.setChecked(false);

			rl_realtime.setVisibility(View.VISIBLE);
			ll_detaildata.setVisibility(View.GONE);
			lv_history.setVisibility(View.GONE);
			tb_hud.setVisibility(View.VISIBLE);
			break;

		case TAB_RUN:
			tb_hud.setVisibility(View.GONE);
			rl_realtime.setAnimation(null);
			TV_TopMenu_Title.setText(R.string.mileage_top_all);

			if (mIsListView) {
				rl_realtime.setVisibility(View.GONE);
				ll_detaildata.setVisibility(View.GONE);
				lv_history.setVisibility(View.VISIBLE);
			} else {
				rl_realtime.setVisibility(View.GONE);
				ll_detaildata.setVisibility(View.VISIBLE);
				lv_history.setVisibility(View.GONE);
			}

			break;

		case TAB_DAY:
			rl_realtime.setAnimation(null);
			tb_hud.setVisibility(View.GONE);
			TV_TopMenu_Title.setText(R.string.mileage_top_day);

			if (mIsListView) {
				rl_realtime.setVisibility(View.GONE);
				ll_detaildata.setVisibility(View.GONE);
				lv_history.setVisibility(View.VISIBLE);
			} else {
				rl_realtime.setVisibility(View.GONE);
				ll_detaildata.setVisibility(View.VISIBLE);
				lv_history.setVisibility(View.GONE);
			}
			break;

		case TAB_MONTH:
			rl_realtime.setAnimation(null);
			tb_hud.setVisibility(View.GONE);
			TV_TopMenu_Title.setText(R.string.mileage_top_month);

			rl_realtime.setVisibility(View.GONE);
			ll_detaildata.setVisibility(View.VISIBLE);
			lv_history.setVisibility(View.GONE);
			break;
		}

	}

	public static void utilLogVid(byte[] orgData) {

		byte[] buf = new byte[17];
		System.arraycopy(orgData, 2, buf, 0, 17);

		int dat = BtUtil.Bytes2Int(buf);// ��

		RbLog.d(TAG, "Vid :" + dat);
	}

	public static Calendar utilGetCalendar(int sec) {
		Calendar calendar = Calendar.getInstance();
		// calendar.set(2012, 1, 1, 0, 0);
		calendar.set(Calendar.YEAR, 2012);
		calendar.set(Calendar.MONTH, Calendar.JANUARY);
		calendar.set(Calendar.DAY_OF_MONTH, 1);

		calendar.set(Calendar.HOUR_OF_DAY, 0);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		calendar.set(Calendar.MILLISECOND, 0);

		calendar.add(Calendar.SECOND, sec);

		return calendar;
	}

	private void showTimeoutDialog() {

		final IKPopup.Builder popup = new IKPopup.Builder(this,
				IKPopup.POPUP_ALERT_ONE_BTN,
				getString(R.string.popup_type_information),
				getString(R.string.popup_sync), getString(R.string.btn_ok),
				getString(R.string.btn_no));
		final Dialog dlg = popup.create();
		popup.setOnIKPopuoClickListener(new onIKPopupClickListener() {
			@Override
			public void onIKPopUpClick(View v) {
				switch (v.getId()) {
				case R.id.B_Popup_Ok:
					dlg.dismiss();
					break;
				case R.id.B_Popup_Cancel:
					dlg.dismiss();
					break;
				}
			}
		});
		dlg.setCancelable(false);
		dlg.show();
	}

	class GetRealTimeDataThread extends Thread {
		boolean cancel = false;

		public void cancel() {
			cancel = true;
		}

		public void run() {
			while (cancel == false) {

				if (mSelectTab != TAB_REALTIME)
					break;

				RbLog.d(TAG, "GetRealTimeDataThread");

				BtService.getBtService().OBD_Request(
						BtService.OBD_GET_REAL_DRIVER, null,
						NewMileageActivity.this);

				// get speed cool
				byte[] reqData = { 0x0D };

				try {
					mRealTimeSpeed = BtService.getBtService()
							.OBD_requestGenericServiceData2(reqData);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				// get something.
				byte[] reqData1 = { 0x05 };

				try {
					mRealTimeCool = BtService.getBtService()
							.OBD_requestGenericServiceData2(reqData1);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				// get something.
				mRealTimeVolt = BtService.getBtService().OBD_VOLTAGE();
				RbLog.d(TAG, "Realtimelog s:" + mRealTimeSpeed + " c:"
						+ mRealTimeCool + " v:" + mRealTimeVolt);
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					;
				}
			}
		}
	}

	private void realTimeDataParse(byte[] REAL) {

		if (REAL == null)
			return;

		RbLog.d(TAG, "realTimeDataParse");

		byte[] dummy = { 0, 0, 0, 0 };
		dummy[0] = REAL[0];
		dummy[1] = REAL[1];
		dummy[2] = REAL[2];
		dummy[3] = REAL[3];
		data0 = BtUtil.Bytes2Int(dummy);

		dummy[0] = REAL[4];
		dummy[1] = REAL[5];
		dummy[2] = REAL[6];
		dummy[3] = REAL[7];
		data1 = BtUtil.Bytes2Int(dummy);

		dummy[0] = REAL[8];
		dummy[1] = REAL[9];
		dummy[2] = REAL[10];
		dummy[3] = REAL[11];
		data2 = BtUtil.Bytes2Int(dummy);

		if (mRealtimeDriveDistanceCheckCnt < 20) {
			mRealtimeDriveDistanceCheckCnt++;
			mRealtimeDriveDistance += data2;

			RbLog.e(TAG, " mRealtimeDriveDistanceCheckCnt : "
					+ mRealtimeDriveDistanceCheckCnt);
			// check
			int sumIndex = 0;
			for (int cntIndex = 0; cntIndex < 20; cntIndex++) {

				sumIndex += (int) REAL[cntIndex];

			}

			RbLog.d(TAG, "--- sumIndex --- : " + sumIndex);
			if (sumIndex == 0) {
				mRealtimeDriveIsValid = false;
			} else {
				mRealtimeDriveIsValid = true;
			}
		} else {
			if (mRealtimeDriveIsValid == false) {
				RbLog.e(TAG,
						" = = = = =mRealtimeDriveIsValid == false = = = = =");
				viewSelectTab(TAB_RUN, true);
				return;
			}
		}

		second = data1 % 60;
		minute = (data1 / 60) % 60;
		cigan = (data1 / 3600) % 24;
		day = (data1 / 86400) % 30;
		month = (data1 / 2592000) % 12;

	}

	private void viewUpdateRealTimeData() {
		RbLog.d(TAG, "viewUpdateRealTimeData");

		// if (REAL != null) {

		cal2.set(2012, 0, 1, 0, 0, 0);
		cal2.add(Calendar.SECOND, data1);
		SimpleDateFormat dFormat = new SimpleDateFormat("mm:ss");

		TextView starttime = (TextView) findViewById(R.id.text_mileage1);

		if (cal2.get(Calendar.HOUR_OF_DAY) < 10)
			starttime.setText("0" + cal2.get(Calendar.HOUR_OF_DAY) + ":"
					+ dFormat.format(cal2.getTime()));
		else
			starttime.setText("" + cal2.get(Calendar.HOUR_OF_DAY) + ":"
					+ dFormat.format(cal2.getTime()));

		TextView realtime = (TextView) findViewById(R.id.text_mileage2);
		Calendar cal = Calendar.getInstance();
		cal.set(2012, 0, 1, 0, 0, 0);
		cal.add(Calendar.SECOND, data0 / 1000);
		dFormat = new SimpleDateFormat("mm:ss");

		if (cal.get(Calendar.HOUR_OF_DAY) < 10)
			realtime.setText("0" + cal.get(Calendar.HOUR_OF_DAY) + ":"
					+ dFormat.format(cal.getTime()));
		else
			realtime.setText("" + cal.get(Calendar.HOUR_OF_DAY) + ":"
					+ dFormat.format(cal.getTime()));
		RbLog.d(TAG, "real speed : " + data0);

		TextView distance = (TextView) findViewById(R.id.text_mileage3);
		String strAppVersion = String.format("%.1f", (float) data2 / 10);
		distance.setText("" + strAppVersion + " Km");
		// //
		// if (data3 == 0x01) {// ����
		// TextView mileage = (TextView) findViewById(R.id.text_mileage4);
		// strAppVersion = String.format("%.1f", (float) data4 / 10);
		// mileage.setText("" + strAppVersion + " Km/L");
		// } else {
		// TextView mileage = (TextView) findViewById(R.id.text_mileage4);
		// mileage.setText(getString(R.string.unsupported));
		// }
		//
		// if (data5 == 0x01) {// ����Ҹ�
		// TextView mileage = (TextView) findViewById(R.id.text_mileage5);
		// strAppVersion = String.format("%.1f", (float) data6 / 10);
		// mileage.setText("" + strAppVersion + " L");
		// } else {
		// TextView mileage = (TextView) findViewById(R.id.text_mileage5);
		// mileage.setText(getString(R.string.unsupported));
		// }
		//
		// if (data7 == 0x01) {// Fuel Level
		// TextView mileage = (TextView) findViewById(R.id.text_mileage6);
		// String strAppVersion1 = String.format("%.1f",
		// (float) data8 * 100 / 255);
		// mileage.setText("" + strAppVersion1 + " %");
		// } else {
		// TextView mileage = (TextView) findViewById(R.id.text_mileage6);
		// mileage.setText(getString(R.string.unsupported));
		// }
		//
		TextView speed = (TextView) findViewById(R.id.text_mileage7);
		int i2 = 0;
		if (mRealTimeSpeed != null) {
			if (mRealTimeSpeed[0] == 0x00) {
				speed.setText(getString(R.string.unsupported));
			} else {
				byte[] ag = new byte[1];
				ag[0] = mRealTimeSpeed[1];
				i2 = BtUtil.Bytes2Int(ag);
				speed.setText("" + i2 + " Km/h");
			}
		}

		if (mRealTimeCool != null) {
			if (mRealTimeCool[0] == 0x00) {
				TextView coolant = (TextView) findViewById(R.id.text_mileage8);
				coolant.setText(getString(R.string.unsupported));
				// coolant.setText("" + (a2[1] - 40));// -40��
			} else {
				byte[] ag = new byte[1];
				ag[0] = mRealTimeCool[1];
				int i = BtUtil.Bytes2Int(ag);
				TextView coolant = (TextView) findViewById(R.id.text_mileage8);
				// strAppVersion1 = String.format("%u", (a2[0] - 40));
				coolant.setText("" + (i - 40) + "℃");
			}
		}

		if (mRealTimeVolt != null) {

			RbLog.d(TAG, "mRealTimeVolt : " + mRealTimeVolt);

			int b1 = BtUtil.Bytes2Int(mRealTimeVolt);
			TextView battery = (TextView) findViewById(R.id.text_mileage9);
			strAppVersion = String.format("%.2f", (float) b1 * 0.004384);
			battery.setText("" + strAppVersion + "V");
		}

		// TextView grade = (TextView) findViewById(R.id.grade);
		// if (i2 > 80){
		// grade.setText("B");
		// }else if(i2 > 110){
		// grade.setText("C");
		// }
		// ///////////////////////////////////////////////////
		// Display display =
		// ((WindowManager)getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
		// int displayHeight = display.getHeight();
		// if (displayHeight > 720) {
		// starttime = (TextView) findViewById(R.id.text_mileage1);
		// starttime.setTextSize(50);
		// starttime = (TextView) findViewById(R.id.text_mileage_1);
		// starttime.setTextSize(50);
		//
		// realtime = (TextView) findViewById(R.id.text_mileage2);
		// realtime.setTextSize(50);
		// realtime = (TextView) findViewById(R.id.text_mileage_2);
		// realtime.setTextSize(50);
		//
		// distance = (TextView) findViewById(R.id.text_mileage3);
		// distance.setTextSize(50);
		// distance = (TextView) findViewById(R.id.text_mileage_3);
		// distance.setTextSize(50);
		//
		// // TextView mileage = (TextView)
		// findViewById(R.id.text_mileage4);
		// // mileage.setTextSize(50);
		// // mileage = (TextView) findViewById(R.id.text_mileage_4);
		// // mileage.setTextSize(50);
		// //
		// // mileage = (TextView) findViewById(R.id.text_mileage5);
		// // mileage.setTextSize(50);
		// // mileage = (TextView) findViewById(R.id.text_mileage_5);
		// // mileage.setTextSize(50);
		// //
		// // mileage = (TextView) findViewById(R.id.text_mileage6);
		// // mileage.setTextSize(50);
		// // mileage = (TextView) findViewById(R.id.text_mileage_6);
		// // mileage.setTextSize(50);
		//
		// //TextView speed = (TextView)
		// findViewById(R.id.text_mileage7);
		// speed.setTextSize(50);
		// speed = (TextView) findViewById(R.id.text_mileage_7);
		// speed.setTextSize(50);
		//
		// TextView coolant = (TextView)
		// findViewById(R.id.text_mileage8);
		// coolant.setTextSize(50);
		// coolant = (TextView) findViewById(R.id.text_mileage_8);
		// coolant.setTextSize(50);
		//
		// battery = (TextView) findViewById(R.id.text_mileage9);
		// battery.setTextSize(50);
		// battery = (TextView) findViewById(R.id.text_mileage_9);
		// battery.setTextSize(50);
		//
		// }
		// if (displayHeight > 720) {
		// starttime = (TextView) findViewById(R.id.text_mileage1);
		// starttime.setTextSize(35);
		// starttime = (TextView) findViewById(R.id.text_mileage_1);
		// starttime.setTextSize(35);
		//
		// realtime = (TextView) findViewById(R.id.text_mileage2);
		// realtime.setTextSize(35);
		// realtime = (TextView) findViewById(R.id.text_mileage_2);
		// realtime.setTextSize(35);
		//
		// distance = (TextView) findViewById(R.id.text_mileage3);
		// distance.setTextSize(35);
		// distance = (TextView) findViewById(R.id.text_mileage_3);
		// distance.setTextSize(35);
		//
		// TextView mileage = (TextView)
		// findViewById(R.id.text_mileage4);
		// mileage.setTextSize(35);
		// mileage = (TextView) findViewById(R.id.text_mileage_4);
		// mileage.setTextSize(35);
		//
		// mileage = (TextView) findViewById(R.id.text_mileage5);
		// mileage.setTextSize(35);
		// mileage = (TextView) findViewById(R.id.text_mileage_5);
		// mileage.setTextSize(35);
		//
		// mileage = (TextView) findViewById(R.id.text_mileage6);
		// mileage.setTextSize(35);
		// mileage = (TextView) findViewById(R.id.text_mileage_6);
		// mileage.setTextSize(35);
		//
		// TextView speed = (TextView) findViewById(R.id.text_mileage7);
		// speed.setTextSize(35);
		// speed = (TextView) findViewById(R.id.text_mileage_7);
		// speed.setTextSize(35);
		//
		// TextView coolant = (TextView)
		// findViewById(R.id.text_mileage8);
		// coolant.setTextSize(35);
		// coolant = (TextView) findViewById(R.id.text_mileage_8);
		// coolant.setTextSize(35);
		//
		// battery = (TextView) findViewById(R.id.text_mileage9);
		// battery.setTextSize(35);
		// battery = (TextView) findViewById(R.id.text_mileage_9);
		// battery.setTextSize(35);
		//
		// }
		// /////////////////////////////////////////////////////

		// } else {
		//
		// TextView coolant = (TextView) findViewById(R.id.text_mileage5);
		// coolant.setText("BT X");
		// coolant.setTextSize(35);
		// }
		// };

	};

	private void getMileageData(int viewmode) {

		RbLog.d(TAG, "getMileageData " + viewmode);
		mDriveDetailArrayList.clear();

		switch (viewmode) {

		case TAB_REALTIME:
			new GetRealTimeDataThread().start();
			break;

		case TAB_RUN:
		case TAB_DAY:
			if (mIsListView) {
				new GetHistoryThread().start();
			} else {
				new GetDeatailDataThread().start();
			}
			break;

		case TAB_MONTH:
			new GetDeatailDataThread().start();
			break;

		}

	}

	class GetHistoryThread extends Thread {
		boolean cancel = false;

		public void cancel() {
			cancel = true;
			GetHistoryUpdateHandler.removeCallbacksAndMessages(null);
		}

		public void run() {
			RbLog.d(TAG, "GetHistoryThread mSelectTab:" + mSelectTab);

			GetHistoryUpdateHandler.sendMessage(GetHistoryUpdateHandler
					.obtainMessage(0));

			// open db.
			OBDDbHelper mMileageDBHelper = new OBDDbHelper(
					NewMileageActivity.this);
			SQLiteDatabase db = mMileageDBHelper.getReadableDatabase();

			switch (mSelectTab) {

			case TAB_RUN: {

				// Cursor mCursor = db.rawQuery("SELECT title FROM dic", null);
				Cursor mCursor = db.rawQuery(
						"SELECT * FROM dic ORDER BY start desc", null);

				RbLog.d(TAG, "cursor cnt:" + mCursor.getCount());

				while (mCursor.moveToNext()) {

					int startTimeVtalk = mCursor.getInt(1);
					RbLog.d(TAG, "starttime " + startTimeVtalk);
					Calendar startTimeCal = utilGetCalendar(startTimeVtalk);

					mDriveHistoryArrayList.add(new DriveHistoryEntity(
							startTimeVtalk));

					// Collections.reverse(mDriveHistoryArrayList);

				}
				mCursor.close();
				break;
			}

			case TAB_DAY: {

				Calendar lastInsertDate = null; // Calendar.getInstance();

				// Cursor mCursor = db.rawQuery("SELECT title FROM dic", null);
				Cursor mCursor = db.rawQuery(
						"SELECT * FROM dic ORDER BY start desc", null);

				while (mCursor.moveToNext()) {

					int startTimeVtalk = mCursor.getInt(1);
					Calendar startTimeCal = utilGetCalendar(startTimeVtalk);

					// // add
					// lastInsertDate = startTimeCal;
					// mDriveHistoryArrayList.add(new DriveHistoryEntity(
					// startTimeVtalk));

					if (lastInsertDate != null) {
						RbLog.d(TAG,
								"YEAR : " + startTimeCal.get(Calendar.YEAR)
										+ "YEAR : "
										+ lastInsertDate.get(Calendar.YEAR));
						RbLog.d(TAG,
								"MONTH : " + startTimeCal.get(Calendar.MONTH)
										+ "MONTH : "
										+ lastInsertDate.get(Calendar.MONTH));
						RbLog.d(TAG,
								"DAY : "
										+ startTimeCal
												.get(Calendar.DAY_OF_MONTH)
										+ "DAY : "
										+ lastInsertDate
												.get(Calendar.DAY_OF_MONTH));
					}
					if (lastInsertDate == null) {
						// add
						lastInsertDate = startTimeCal;

						mDriveHistoryArrayList.add(new DriveHistoryEntity(
								startTimeVtalk));

					} else if ((lastInsertDate.get(Calendar.YEAR) == startTimeCal
							.get(Calendar.YEAR)
							&& lastInsertDate.get(Calendar.MONTH) == startTimeCal
									.get(Calendar.MONTH) && lastInsertDate
								.get(Calendar.DAY_OF_MONTH) == startTimeCal
							.get(Calendar.DAY_OF_MONTH)) == false) {

						lastInsertDate = startTimeCal;
						mDriveHistoryArrayList.add(new DriveHistoryEntity(
								startTimeVtalk));

					}
				}
				mCursor.close();
				break;
			}

			case TAB_MONTH: {

				Calendar lastMonth = Calendar.getInstance();
				lastMonth.add(Calendar.MONTH, -1);
				lastMonth.add(Calendar.DAY_OF_MONTH, -1);
				utilLogDate(lastMonth);

				// Cursor mCursor = db.rawQuery("SELECT title FROM dic", null);
				Cursor mCursor = db.rawQuery(
						"SELECT * FROM dic ORDER BY start", null);
				while (mCursor.moveToNext()) {

					int startTimeVtalk = mCursor.getInt(1);
					Calendar startTimeCal = utilGetCalendar(startTimeVtalk);

					if (startTimeCal.after(lastMonth)) {
						mDriveHistoryArrayList.add(new DriveHistoryEntity(
								startTimeVtalk));
					}

				}
				mCursor.close();
				break;
			}
			}

			db.close();

			// // show data
			// if (mDriveHistoryArrayList.size() > 0) {
			// // msg.what=2;
			// RbLog.d(TAG, "mDriveHistoryArrayList.size cnt:"
			// + mDriveHistoryArrayList.size());
			// try {
			// RbLog.d(TAG, "try");
			// GetHistoryUpdateHandler.sendMessage(GetHistoryUpdateHandler
			// .obtainMessage(2));
			// } catch (Exception e) {
			// // TODO Auto-generated catch block
			// RbLog.d(TAG, "catch");
			// e.printStackTrace();
			// }
			//
			// }
			// close progress
			try {
				GetHistoryThread.sleep(900);
				GetHistoryUpdateHandler.sendMessage(GetHistoryUpdateHandler
						.obtainMessage(1));
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	class GetDeatailDataThread extends Thread {
		boolean cancel = false;

		public void cancel() {
			cancel = true;
			GetDetailDataUpdateHandler.removeCallbacksAndMessages(null);
		}

		public void run() {
			RbLog.d(TAG, "GetHistoryThread mSelectTab:" + mSelectTab);

			// Message msg = new Message();
			// msg.what=0;
			GetDetailDataUpdateHandler.sendMessage(GetDetailDataUpdateHandler
					.obtainMessage(0));

			OBDDbHelper mMileageDBHelper = new OBDDbHelper(
					NewMileageActivity.this);
			SQLiteDatabase db = mMileageDBHelper.getReadableDatabase();

			// month
			// day
			// run
			// getDriveDetailEntity(term);

			Calendar driveDetailStartCal = utilGetCalendar(mDriveDetailStartTime);

			switch (mSelectTab) {

			case TAB_RUN: {

				Cursor mCursor = db.rawQuery(
						"SELECT * FROM dic ORDER BY start", null);

				RbLog.d(TAG, "cursor cnt:" + mCursor.getCount());

				while (mCursor.moveToNext()) {

					int startTimeVtalk = mCursor.getInt(1);
					Calendar startTimeCal = utilGetCalendar(startTimeVtalk);

					if (startTimeVtalk == mDriveDetailStartTime)
					// if (mDriveDetailStartTime.equals(startTime))startTime

					// if (mDriveDetailStartTime.get(Calendar.YEAR) == startTime
					// .get(Calendar.YEAR)
					// && mDriveDetailStartTime.get(Calendar.MONTH) == startTime
					// .get(Calendar.MONTH)
					// && mDriveDetailStartTime.get(Calendar.DAY_OF_MONTH) ==
					// startTime
					// .get(Calendar.DAY_OF_MONTH)
					// && mDriveDetailStartTime.get(Calendar.HOUR_OF_DAY) ==
					// startTime
					// .get(Calendar.HOUR_OF_DAY)
					// && mDriveDetailStartTime.get(Calendar.SECOND) ==
					// startTime
					// .get(Calendar.SECOND))
					{
						DriveDetailEntity entity = new DriveDetailEntity(
								mCursor);
						// RbLog.d(TAG, "entity.maxVss (mileage)   :   "
						// + entity.maxVss);
						RbLog.d(TAG, "entity (avgCool) :" + entity.avgCool);
						RbLog.d(TAG, "entity (supCool) :" + entity.supCool);
						RbLog.d(TAG, "entity (maxCool) :" + entity.maxCool);
						RbLog.d(TAG, "Add Item ");
						utilLogDate(startTimeCal);
						mDriveDetailArrayList.add(entity);
					}

				}
				mCursor.close();
				break;
			}

			case TAB_DAY: {

				// Calendar lastInsertDate = null; // Calendar.getInstance();

				// Cursor mCursor = db.rawQuery("SELECT title FROM dic", null);
				Cursor mCursor = db.rawQuery(
						"SELECT * FROM dic ORDER BY start", null);
				while (mCursor.moveToNext()) {

					int startTimeVtalk = mCursor.getInt(1);
					Calendar startTimeCal = utilGetCalendar(startTimeVtalk);

					// if (lastInsertDate == null) {
					// // add
					// lastInsertDate = startTimeCal;
					//
					// mDriveDetailArrayList.add(entity);
					//
					// } else
					if (driveDetailStartCal.get(Calendar.YEAR) == startTimeCal
							.get(Calendar.YEAR)
							&& driveDetailStartCal.get(Calendar.MONTH) == startTimeCal
									.get(Calendar.MONTH)
							&& driveDetailStartCal.get(Calendar.DAY_OF_MONTH) == startTimeCal
									.get(Calendar.DAY_OF_MONTH)) {

						DriveDetailEntity entity = new DriveDetailEntity(
								mCursor);
						RbLog.d(TAG, "Add Item ");
						utilLogDate(startTimeCal);
						mDriveDetailArrayList.add(entity);
					}
				}

				mCursor.close();
				break;
			}

			case TAB_MONTH: {

				Calendar lastMonth = Calendar.getInstance();
				lastMonth.add(Calendar.MONTH, -1);
				lastMonth.add(Calendar.DAY_OF_MONTH, -1);
				utilLogDate(lastMonth);

				Cursor mCursor = db.rawQuery(
						"SELECT * FROM dic ORDER BY start", null);
				while (mCursor.moveToNext()) {

					int startTimeVtalk = mCursor.getInt(1);
					Calendar startTimeCal = utilGetCalendar(startTimeVtalk);

					DriveDetailEntity entity = new DriveDetailEntity(mCursor);

					if (startTimeCal.after(lastMonth)) {
						RbLog.d(TAG, "Add Item ");
						utilLogDate(startTimeCal);
						mDriveDetailArrayList.add(entity);
					}

				}
				mCursor.close();
				break;
			}
			}

			db.close();

			RbLog.d(TAG, "detail data count " + mDriveDetailArrayList.size());

			int dataCnt = mDriveDetailArrayList.size();

			if (mDriveDetailArrayList.size() > 0) {

				mDriveDetailResultEntity.reset();

				for (int idx = 0; idx < dataCnt; idx++) {

					// peoriod
					switch (mSelectTab) {

					case TAB_RUN: {
						mDriveDetailResultEntity.starttime = mDriveDetailArrayList
								.get(idx).starttime;

						mDriveDetailResultEntity.endtime = mDriveDetailArrayList
								.get(idx).endtime;
						break;
					}
					case TAB_DAY: {
						mDriveDetailResultEntity.starttime = mDriveDetailArrayList
								.get(idx).starttime;
						break;
					}
					case TAB_MONTH: {
						// mDriveDetailResultEntity.starttime =
						// mDriveDetailArrayList
						// .get(idx).starttime;
						break;
					}
					}

					mDriveDetailResultEntity.drivingTimeSec += (mDriveDetailArrayList
							.get(idx).endtime - mDriveDetailArrayList.get(idx).starttime);

					mDriveDetailResultEntity.mileage += mDriveDetailArrayList
							.get(idx).mileage;
					mDriveDetailResultEntity.maxVss += mDriveDetailArrayList
							.get(idx).maxVss;
					mDriveDetailResultEntity.supBat += mDriveDetailArrayList
							.get(idx).supBat;
					mDriveDetailResultEntity.avgBat += mDriveDetailArrayList
							.get(idx).avgBat;
					mDriveDetailResultEntity.minBat += mDriveDetailArrayList
							.get(idx).minBat;
					mDriveDetailResultEntity.maxBat += mDriveDetailArrayList
							.get(idx).maxBat;
					mDriveDetailResultEntity.supCool += mDriveDetailArrayList
							.get(idx).supCool;
					mDriveDetailResultEntity.avgCool += mDriveDetailArrayList
							.get(idx).avgCool;
					mDriveDetailResultEntity.maxCool += mDriveDetailArrayList
							.get(idx).maxCool;
					mDriveDetailResultEntity.supEngine += mDriveDetailArrayList
							.get(idx).supEngine;
					mDriveDetailResultEntity.avgEngine += mDriveDetailArrayList
							.get(idx).avgEngine;
					mDriveDetailResultEntity.maxEngine += mDriveDetailArrayList
							.get(idx).maxEngine;
					mDriveDetailResultEntity.supEff += mDriveDetailArrayList
							.get(idx).supEff;
					mDriveDetailResultEntity.avgEff += mDriveDetailArrayList
							.get(idx).avgEff;
					mDriveDetailResultEntity.supfuelUse += mDriveDetailArrayList
							.get(idx).supfuelUse;
					mDriveDetailResultEntity.fuelUse += mDriveDetailArrayList
							.get(idx).fuelUse;
					mDriveDetailResultEntity.decelCnt += mDriveDetailArrayList
							.get(idx).decelCnt;
					mDriveDetailResultEntity.accelCnt += mDriveDetailArrayList
							.get(idx).accelCnt;
					mDriveDetailResultEntity.avgVss += mDriveDetailArrayList
							.get(idx).avgVss;
					mDriveDetailResultEntity.idling += mDriveDetailArrayList
							.get(idx).idling;
					mDriveDetailResultEntity.maxRpm += mDriveDetailArrayList
							.get(idx).maxRpm;

				}

				if (dataCnt > 1) {

					// mDriveDetailResultEntity.mileage =
					// mDriveDetailResultEntity.mileage
					// / dataCnt;
					mDriveDetailResultEntity.maxVss = mDriveDetailResultEntity.maxVss
							/ dataCnt;
					mDriveDetailResultEntity.supBat = mDriveDetailResultEntity.supBat
							/ dataCnt;
					mDriveDetailResultEntity.avgBat = mDriveDetailResultEntity.avgBat
							/ dataCnt;
					mDriveDetailResultEntity.minBat = mDriveDetailResultEntity.minBat
							/ dataCnt;
					mDriveDetailResultEntity.maxBat = mDriveDetailResultEntity.maxBat
							/ dataCnt;
					mDriveDetailResultEntity.supCool = mDriveDetailResultEntity.supCool
							/ dataCnt;
					mDriveDetailResultEntity.avgCool = mDriveDetailResultEntity.avgCool
							/ dataCnt;
					mDriveDetailResultEntity.maxCool = mDriveDetailResultEntity.maxCool
							/ dataCnt;
					mDriveDetailResultEntity.supEngine = mDriveDetailResultEntity.supEngine
							/ dataCnt;
					mDriveDetailResultEntity.avgEngine = mDriveDetailResultEntity.avgEngine
							/ dataCnt;
					mDriveDetailResultEntity.maxEngine = mDriveDetailResultEntity.maxEngine
							/ dataCnt;
					mDriveDetailResultEntity.supEff = mDriveDetailResultEntity.supEff
							/ dataCnt;
					mDriveDetailResultEntity.avgEff = mDriveDetailResultEntity.avgEff
							/ dataCnt;
					mDriveDetailResultEntity.supfuelUse = mDriveDetailResultEntity.supfuelUse
							/ dataCnt;
					mDriveDetailResultEntity.fuelUse = mDriveDetailResultEntity.fuelUse
							/ dataCnt;
					mDriveDetailResultEntity.decelCnt = mDriveDetailResultEntity.decelCnt
							/ dataCnt;
					mDriveDetailResultEntity.accelCnt = mDriveDetailResultEntity.accelCnt
							/ dataCnt;
					mDriveDetailResultEntity.avgVss = mDriveDetailResultEntity.avgVss
							/ dataCnt;
					mDriveDetailResultEntity.idling = mDriveDetailResultEntity.idling
							/ dataCnt;
					mDriveDetailResultEntity.maxRpm = mDriveDetailResultEntity.maxRpm
							/ dataCnt;
				}

			}

			// close progress
			GetDetailDataUpdateHandler.sendMessage(GetDetailDataUpdateHandler
					.obtainMessage(1));

			// send message to update
			if (mDriveDetailArrayList.size() > 0) {

				GetDetailDataUpdateHandler
						.sendMessage(GetDetailDataUpdateHandler
								.obtainMessage(2));

			}
		}
	}

	/*
	 * public void db_index_scan() {
	 * 
	 * db = mHelper2.getReadableDatabase(); cursor =
	 * db.rawQuery("SELECT title FROM dic", null);
	 * 
	 * if (cursor.moveToNext()) index_int = cursor.getInt(0);
	 * 
	 * if (index_int > 27399) index_int = 0;
	 * 
	 * RbLog.d(TAG, "mHelper2 index_int:" + index_int);
	 * 
	 * db.close(); cursor.close(); }
	 */

	private void utilLogDate(Calendar val) {

		int month = val.get(Calendar.MONTH) + 1;

		RbLog.d(TAG,
				"Debug : " + val.get(Calendar.YEAR) + month
						+ val.get(Calendar.DATE) + " "
						+ val.get(Calendar.HOUR_OF_DAY) + " "
						+ val.get(Calendar.MINUTE) + " "
						+ val.get(Calendar.SECOND));
	}

	private Handler GetHistoryUpdateHandler = new Handler() {
		public void handleMessage(Message msg) {

			// progress start
			if (msg.what == 0) {

				// lv_history.setAdapter(null);
				pd = new ProgressDialog(NewMileageActivity.this);
				pd = ProgressDialog.show(NewMileageActivity.this,
						"Driving Info Loading",
						"OBD에서 DATA 읽어오는중...\n 잠시만 기다려주십시오.");
			}
			// progress end
			else if (msg.what == 1) {
				RbLog.d(TAG, " GetHistoryUpdateHandler msg : 1 ");
				pd.dismiss();
				lv_history.setAdapter(mMileageHistoryAdapter);
				mMileageHistoryAdapter.notifyDataSetChanged();
				if (mDriveHistoryArrayList.size() > 0) {
					lv_history
							.setOnItemClickListener(new OnItemClickListener() {

								@Override
								public void onItemClick(AdapterView<?> arg0,
										View arg1, int position, long l_position) {
									RbLog.d(TAG, "user select position "
											+ position);

									RbLog.d(TAG,
											"user select title "
													+ mDriveHistoryArrayList
															.get(position).title);

									mDriveDetailStartTime = mDriveHistoryArrayList
											.get(position).startTime;

									/*
									 * Intent intent = new
									 * Intent(NewMileageActivity.this,
									 * MileageHistoryDetailActivity.class);
									 * intent.putExtra("HISTORY", position);
									 * startActivityForResult(intent, 0);
									 */

									// mSelectTab = VIEWMODE_RUN;
									mIsListView = false;
									viewUpdate(mSelectTab);
									getMileageData(mSelectTab);

								}
							});
				}
			} else if (msg.what == 2) {
				RbLog.d(TAG, " GetHistoryUpdateHandler msg : 2");
				// ArrayList<DriveHistoryEntity> mileageTempArrayList = new
				// ArrayList<DriveHistoryEntity>();
				// mileageTempArrayList = mHistoryArrayList;
				// Collections.reverse(mileageTempArrayList);

				// make arraylist
				// array adapter
				// lv_history.setAdapter(mMileageHistoryAdapter);
				// ////////////////////////////////////////////////////////
				// mMileageHistoryAdapter.notifyDataSetChanged();
				// RbLog.d(TAG,
				// " GetHistoryUpdateHandler msg : 2 after notify");
				// lv_history.setOnItemClickListener(new OnItemClickListener() {
				//
				// @Override
				// public void onItemClick(AdapterView<?> arg0, View arg1,
				// int position, long l_position) {
				// RbLog.d(TAG, "user select position " + position);
				//
				// RbLog.d(TAG, "user select title "
				// + mDriveHistoryArrayList.get(position).title);
				//
				// mDriveDetailStartTime = mDriveHistoryArrayList
				// .get(position).startTime;
				//
				// /*
				// * Intent intent = new Intent(NewMileageActivity.this,
				// * MileageHistoryDetailActivity.class);
				// * intent.putExtra("HISTORY", position);
				// * startActivityForResult(intent, 0);
				// */
				//
				// // mSelectTab = VIEWMODE_RUN;
				// mIsListView = false;
				// viewUpdate(mSelectTab);
				// getMileageData(mSelectTab);
				//
				// }
				// });

				// ////////////////////////////////////////////////////////
				// 1번의 디스미스 위에 2번 내용을 넣고 if (mDriveHistoryArrayList.size() > 0)
				// { 조건문단다

				// click item
				// mIsListView = false;
				// viewUpdate(mSelectTab);
				// getMileageData(mSelectTab);

				// Adapter =new
				// ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,
				// mArrayList);
				// mListAdapter = new DiagHistoryListAdapter(this,
				// R.layout.diaghistory_list_layout, mArrayList);
				// ����� ����
				// ListView list = (ListView) findViewById(R.id.mileage_list);
				// list.setAdapter(Adapter);
				// list.setOnItemClickListener(new OnItemClickListener() {
				// public void onItemClick(AdapterView<?> argc0, View view,
				// int position, long id) {
				//
				// if (server) {
				// String mes = "" + mArrayList.get(position);
				// RbLog.d("PNI", "i:" + index_int);
				// String a2 = Integer.toString(index_int);
				// String a = mes.substring(2, 2 + a2.length() + 1);
				// if (a.contains(" "))
				// a = mes.substring(2, 2 + a2.length() - 0);
				//
				// if (a.contains(" "))
				// a = mes.substring(2, 2 + a2.length() - 1);
				//
				// if (a.contains(" "))
				// a = mes.substring(2, 2 + a2.length() - 2);
				//
				// if (a.contains(" "))
				// a = mes.substring(2, 2 + a2.length() - 3);
				//
				// Intent intent = new Intent(NewMileageActivity.this,
				// MileageHistoryDetailActivity.class);
				// intent.putExtra("HISTORY", Integer.parseInt(a));
				// startActivityForResult(intent, 0);
				// } else
				// Toast.makeText(NewMileageActivity.this,
				// "서버 통신에 실패하여 상세내역을 가져오지 못하였습니다.",
				// Toast.LENGTH_SHORT).show();
				// }
				// });

			}
		}

	};

	private Handler GetDetailDataUpdateHandler = new Handler() {
		public void handleMessage(Message msg) {

			if (msg.what == 0) {

				if (pd != null) {
					pd.dismiss();
				}
				pd = new ProgressDialog(NewMileageActivity.this);
				pd = ProgressDialog.show(NewMileageActivity.this,
						"Driving Info Loading",
						"OBD에서 DATA 읽어오는중...\n 잠시만 기다려주십시오.");
			} else if (msg.what == 1) {
				pd.dismiss();
			} else if (msg.what == 2) {
				viewUpdateDriveDetailData();
			}
		}

	};

	class MileageDBHelper2 extends SQLiteOpenHelper {
		public MileageDBHelper2(Context context) {
			super(context, "Mileage50.db", null, 1);
		}

		public void onCreate(SQLiteDatabase db) {
			// db.execSQL("create table dic (_id integer primary key autoincrement, "
			// + "title text not null);");
			db.execSQL("CREATE TABLE dic (title TEXT)");

		}

		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			db.execSQL("DROP TABLE IF EXISTS dic");
			onCreate(db);
		}
	}

	// void selectTab(int tabIndex) {
	// mSelectTab = VIEWMODE_REALTIME;
	//
	// if (mSelectTab == VIEWMODE_RUN || mSelectTab == VIEWMODE_DAY)
	// mIsListView = true;
	// else
	// mIsListView = false;
	//
	// viewUpdate(mSelectTab);
	//
	// // do something(getdata)
	// getMileageData(mSelectTab);
	// }

	@Override
	public void onClick(View v) {

		switch (v.getId()) {

		case R.id.B_TopMenu_Left:
			finish();
			break;

		case R.id.bt_realtime:
			// 테스트용 기존 앱은 아래 주석 풀어야함
			Intent realMileageIntent = new Intent(NewMileageActivity.this, RealMileageActivity.class);
			startActivity(realMileageIntent);
//			mRealtimeDriveDistance = 0;
//			mRealtimeDriveDistanceCheckCnt = 0;
//			viewSelectTab(TAB_REALTIME, false);
			break;

		case R.id.bt_run:
			viewSelectTab(TAB_RUN, false);
			break;

		case R.id.bt_day:

			viewSelectTab(TAB_DAY, false);
			break;

		case R.id.bt_month:
			viewSelectTab(TAB_MONTH, false);

			break;
		case R.id.tb_hud:
			if (tb_hud.isChecked()) {
				rl_realtime.startAnimation(new MirrorMode());
			} else {
				rl_realtime.startAnimation(new OriginMode());
			}

			break;
		}

	}

	@Override
	public void onNetworkEvent(int type, Object retObject) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onOBDEvent(int type, Object retObject) {
		Log.e(TAG, "onOBDEvent " + type);

		byte[] data = (byte[]) retObject;
		if (data == null) {
			Log.e(TAG, "onOBDEvent ret data is Null, Type:" + type);
		}

		switch (type) {
		case BtService.OBD_GET_COMMUNICATION_START: {

			RbDialog dlg = new RbDialog(this, RbDialog.TITLE, "not response");

			if (data != null && (data[0] == 4 || data[0] == 3 || data[0] == -1)) {
				// Toast.makeText(MainActivity.this, //
				// "start result:" + data[0],
				// Toast.LENGTH_SHOBD_RequestORT).show();
				// if () {
				// showTimeoutDialog2();
			} else {
				// startActivity(new Intent(MainActivity.this,drivingTimeSec
				// DiagActivity.class));
				// overridePendingTransition(0, 0);
			}
			break;
		}

		case BtService.OBD_GET_REAL_DRIVER: {
			realTimeDataParse(data);
			viewUpdateRealTimeData();
			break;
		}

		default:
			break;
		}

	}

	// private void getDriveDetailEntity(byte[] data) {
	//
	// System.arraycopy(data, 2, mDriveDetailEntity.vid, 0, 17);
	// System.arraycopy(data, 19, mDriveDetailEntity.start, 0, 4);
	// System.arraycopy(data, 23, mDriveDetailEntity.end, 0, 4);
	// System.arraycopy(data, 27, mDriveDetailEntity.mileage, 0, 4);
	// System.arraycopy(data, 31, mDriveDetailEntity.max_speed, 0, 1);
	// // System.arraycopy(data, 32, sup_accel, 0, 1);
	// // System.arraycopy(data, 33, accel, 0, 5);
	// System.arraycopy(data, 38, mDriveDetailEntity.sup_battery, 0, 1);
	// System.arraycopy(data, 39, mDriveDetailEntity.max_battery, 0, 2);
	// System.arraycopy(data, 41, mDriveDetailEntity.min_battery, 0, 2);
	// System.arraycopy(data, 43, mDriveDetailEntity.avg_battery, 0, 2);// //
	// System.arraycopy(data, 45, mDriveDetailEntity.sup_temp, 0, 1);//
	// System.arraycopy(data, 46, mDriveDetailEntity.temp, 0, 3);//
	// System.arraycopy(data, 49, mDriveDetailEntity.sup_oil, 0, 1);//
	// System.arraycopy(data, 50, mDriveDetailEntity.oil, 0, 3);//
	// System.arraycopy(data, 53, mDriveDetailEntity.sup_fuel, 0, 1);//
	// System.arraycopy(data, 54, mDriveDetailEntity.fuel, 0, 2);//
	// System.arraycopy(data, 56, mDriveDetailEntity.sup_consume, 0, 1);
	// System.arraycopy(data, 57, mDriveDetailEntity.consume, 0, 2);
	// System.arraycopy(data, 59, mDriveDetailEntity.rapid, 0, 2);
	// System.arraycopy(data, 61, mDriveDetailEntity.maxrpm, 0, 2);
	// System.arraycopy(data, 63, mDriveDetailEntity.avg_speed, 0, 1);
	// System.arraycopy(data, 64, mDriveDetailEntity.idle, 0, 2);
	// mDriveDetailEntity.startTime =
	// utilGetCalendarFromBuf(mDriveDetailEntity.start);
	// mDriveDetailEntity.endTime =
	// utilGetCalendarFromBuf(mDriveDetailEntity.end);
	// }

	private void viewUpdateDriveDetailData() {

		if (mDriveDetailResultEntity == null) {
			RbLog.d(TAG, "Error data is null");
		}

		RbLog.d(TAG, "vid : " + mDriveDetailResultEntity.vid + "\n"
				+ "starttime : " + mDriveDetailResultEntity.starttime + "\n"
				+ "endtime : " + mDriveDetailResultEntity.endtime + "\n"
				+ "mileage : " + mDriveDetailResultEntity.mileage + "\n"
				+ "maxVss : " + mDriveDetailResultEntity.maxVss + "\n"
				+ "supBat : " + mDriveDetailResultEntity.supBat + "\n"
				+ "avgBat : " + mDriveDetailResultEntity.avgBat + "\n"
				+ "minBat : " + mDriveDetailResultEntity.minBat + "\n"
				+ "maxBat : " + mDriveDetailResultEntity.maxBat + "\n"
				+ "supCool : " + mDriveDetailResultEntity.supCool + "\n"
				+ "avgCool : " + mDriveDetailResultEntity.avgCool + "\n"
				+ "maxCool : " + mDriveDetailResultEntity.maxCool + "\n"
				+ "supEngine : " + mDriveDetailResultEntity.supEngine + "\n"
				+ "avgEngine : " + mDriveDetailResultEntity.avgEngine + "\n"
				+ "maxEngine : " + mDriveDetailResultEntity.maxEngine + "\n"
				+ "supEff : " + mDriveDetailResultEntity.supEff + "\n"
				+ "avgEff : " + mDriveDetailResultEntity.avgEff + "\n"
				+ "supfuelUse : " + mDriveDetailResultEntity.supfuelUse + "\n"
				+ "fuelUse : " + mDriveDetailResultEntity.fuelUse + "\n"
				+ "decelCnt : " + mDriveDetailResultEntity.decelCnt + "\n"
				+ "accelCnt : " + mDriveDetailResultEntity.accelCnt + "\n"
				+ "avgVss : " + mDriveDetailResultEntity.avgVss + "\n"
				+ "idling : " + mDriveDetailResultEntity.idling + "\n"
				+ "maxRpm : " + mDriveDetailResultEntity.maxRpm + "\n"

		);

		switch (mSelectTab) {

		case TAB_REALTIME:
			break;

		case TAB_RUN: {
			tv_starttimeText.setText(R.string.all_start);
			Calendar startCal = utilGetCalendar(mDriveDetailResultEntity.starttime);
			Calendar endCal = utilGetCalendar(mDriveDetailResultEntity.endtime);

			int startMonth = startCal.get(Calendar.MONTH) + 1;
			int endMonth = startCal.get(Calendar.MONTH) + 1;

			String startMinute = String.format("%02d",
					startCal.get(Calendar.MINUTE));
			String endMinute = String.format("%02d",
					endCal.get(Calendar.MINUTE));

			text_mileage00.setText(startCal.get(Calendar.YEAR) + "/"
					+ startMonth + "/" + startCal.get(Calendar.DAY_OF_MONTH)
					+ " " + startCal.get(Calendar.HOUR_OF_DAY) + ":"
					+ startMinute + " ~ " +

					endCal.get(Calendar.YEAR) + "/" + endMonth + "/"
					+ endCal.get(Calendar.DAY_OF_MONTH) + " "
					+ endCal.get(Calendar.HOUR_OF_DAY) + ":" + endMinute

			);
			break;
		}

		case TAB_DAY: {
			tv_starttimeText.setText(R.string.all_date);
			Calendar startCal = utilGetCalendar(mDriveDetailResultEntity.starttime);

			int startMonth = startCal.get(Calendar.MONTH) + 1;

			text_mileage00.setText(startCal.get(Calendar.YEAR) + "/"
					+ startMonth + "/" + startCal.get(Calendar.DAY_OF_MONTH));
			break;
		}

		case TAB_MONTH: {
			tv_starttimeText.setText(R.string.all_date);

			Calendar startCal = Calendar.getInstance(); // utilGetCalendar(mDriveDetailResultEntity.starttime);
			Calendar endCal = Calendar.getInstance();

			endCal.add(Calendar.MONTH, -1);
			endCal.add(Calendar.DAY_OF_MONTH, -1);

			int startMonth = startCal.get(Calendar.MONTH) + 1;
			int endMonth = endCal.get(Calendar.MONTH) + 1;

			text_mileage00.setText(

			endCal.get(Calendar.YEAR) + "/" + endMonth + "/"
					+ endCal.get(Calendar.DAY_OF_MONTH) + " ~ "
					+ startCal.get(Calendar.YEAR) + "/" + startMonth + "/"
					+ startCal.get(Calendar.DAY_OF_MONTH));

			break;
		}
		}

		// driving time
		TextView b = (TextView) findViewById(R.id.text_mileage13);
		// b.setText("" + (car_start.get(Calendar.MONTH)+1) + " / "
		// + car_start.get(Calendar.DAY_OF_MONTH) + "  "
		// + car_start.get(Calendar.HOUR_OF_DAY) + ":"
		// + car_start.get(Calendar.MINUTE) + "" + "   ~   "
		// + (car_end.get(Calendar.MONTH)+1) + " / "
		// + car_end.get(Calendar.DAY_OF_MONTH) + "  "
		// + car_end.get(Calendar.HOUR_OF_DAY) + ":"
		// + car_end.get(Calendar.MINUTE) + "    ");
		// SimpleDateFormat dFormat = new SimpleDateFormat("MM / dd  HH : mm");
		String val = utilGetHTime(mDriveDetailResultEntity.drivingTimeSec);
		b.setText(val);

		b = (TextView) findViewById(R.id.text_mileage14);
		String strAppVersion = String.format("%.1f",
		// (float) BtUtil.Bytes2Int(mDriveDetailResultEntity.mileage) / 10);
				(float) mDriveDetailResultEntity.mileage / 10);
		b.setText("" + strAppVersion + " Km");

		b = (TextView) findViewById(R.id.text_mileage15);
		b.setText("" +
		// BtUtil.Bytes2Int(mDriveDetailResultEntity.max_speed)
				mDriveDetailResultEntity.maxVss + " Km / "
				// + BtUtil.Bytes2Int(mDriveDetailResultEntity.avg_speed[0])
				+ mDriveDetailResultEntity.avgVss + " Km");

		// if (mDriveDetailResultEntity.supBat == (byte) 0x00) {
		if (mDriveDetailResultEntity.supBat == 0) {
			b = (TextView) findViewById(R.id.text_mileage16);
			b.setText(getString(R.string.unsupported));
		} else {
			b = (TextView) findViewById(R.id.text_mileage16);
			String strAppVersion1 = String.format("%.1f V", (float) (
			// BtUtil.Bytes2Int(mDriveDetailResultEntity.max_battery) *
			// 0.004384));
					mDriveDetailResultEntity.minBat) * 0.004384);
			String strAppVersion3 = String.format("%.1f V", (float) (
			// BtUtil.Bytes2Int(mDriveDetailResultEntity.min_battery) *
			// 0.004384));
					mDriveDetailResultEntity.maxBat * 0.004384));
			String strAppVersion2 = String.format("%.1f V", (float) (
			// BtUtil.Bytes2Int(mDriveDetailResultEntity.avg_battery) *
			// 0.004384));
					mDriveDetailResultEntity.avgBat) * 0.004384);
			b.setText("" + strAppVersion3 + " / " + strAppVersion1 + " / "
					+ strAppVersion2);
		}
		// }

		// if (mDriveDetailResultEntity.supCool == (byte) 0x00) {
		if (mDriveDetailResultEntity.supCool == 0) {
			// if (mDriveDetailResultEntity.maxCool == 0
			// && mDriveDetailResultEntity.avgCool == 0) {
			b = (TextView) findViewById(R.id.text_mileage17);
			b.setText(getString(R.string.unsupported));
		} else {
			b = (TextView) findViewById(R.id.text_mileage17);
			b.setText(""
			// + ((BtUtil.Bytes2Int(mDriveDetailResultEntity.temp[0])) - 40)
					+ (mDriveDetailResultEntity.maxCool - 40) + " ℃ / "
					// + (BtUtil.Bytes2Int(temp[1]) - 40) + " / "
					// + (BtUtil.Bytes2Int(mDriveDetailResultEntity.temp[2])
					// -
					// 40)
					+ (mDriveDetailResultEntity.avgCool - 40) + " ℃");
		}
		// }
		// if (mDriveDetailResultEntity.supEngine == (byte) 0x00) {
		if (mDriveDetailResultEntity.supEngine == 0) {
			// if (mDriveDetailResultEntity.avgEngine == 0
			// && mDriveDetailResultEntity.maxEngine == 0) {
			b = (TextView) findViewById(R.id.text_mileage18);
			b.setText(getString(R.string.unsupported));
		} else {
			b = (TextView) findViewById(R.id.text_mileage18);
			b.setText(
			// + (BtUtil.Bytes2Int(mDriveDetailResultEntity.oil[0]) - 40)
			String.valueOf(mDriveDetailResultEntity.avgEngine - 40)
					+ " ℃ / "
					// + (BtUtil.Bytes2Int(mDriveDetailResultEntity.oil[1])
					// -
					// 40)
					// + String.valueOf(mDriveDetailResultEntity.- 40)
					// + " ℃ / "
					// + (BtUtil.Bytes2Int(mDriveDetailResultEntity.oil[2])
					// -
					// 40)
					+ String.valueOf(mDriveDetailResultEntity.maxEngine - 40)
					+ " ℃");
		}
		// }
		b = (TextView) findViewById(R.id.text_mileage19);
		b.setText(""
		// + BtUtil.Bytes2Int(mDriveDetailResultEntity.rapid[0])
				+ mDriveDetailResultEntity.accelCnt + " 회 / "
				// + BtUtil.Bytes2Int(mDriveDetailResultEntity.rapid[1]) +
				// " 회");
				+ mDriveDetailResultEntity.decelCnt + " 회");

		// Toast.makeText(this, rapid[0]+"/"+rapid[1]
		// ,Toast.LENGTH_LONG).show();

		if (mDriveDetailResultEntity.supfuelUse == (byte) 0x00) {
			b = (TextView) findViewById(R.id.text_mileage20);
			b.setText(getString(R.string.unsupported));
		} else {
			b = (TextView) findViewById(R.id.text_mileage20);
			b.setText("" + mDriveDetailResultEntity.fuelUse);
		}

		if (mDriveDetailResultEntity.supEff == (byte) 0x00) {
			b = (TextView) findViewById(R.id.text_mileage21);
			b.setText(getString(R.string.unsupported));
		} else {
			b = (TextView) findViewById(R.id.text_mileage21);
			b.setText("" + mDriveDetailResultEntity.avgEff);
		}
		// if (sup_fuel[0] == (byte) 0x00) {
		// b = (TextView) findViewById(R.id.text_mileage21);
		// b.setText(getString(R.string.unsupported));
		// } else {
		// b = (TextView) findViewById(R.id.text_mileage21);
		// b.setText("" + BtUtil.Bytes2Int(fuel));
		// }

		b = (TextView) findViewById(R.id.text_mileage22);
		b.setText(""
		// + BtUtil.Bytes2Int(mDriveDetailResultEntity.maxrpm)
				+ mDriveDetailResultEntity.maxRpm + " Rpm");

		Calendar cal = Calendar.getInstance();
		cal.set(2012, 0, 1, 0, 0, 0);
		cal.add(Calendar.SECOND,
		// BtUtil.Bytes2Int(mDriveDetailResultEntity.idle)
				mDriveDetailResultEntity.idling);
		b = (TextView) findViewById(R.id.text_mileage24);
		b.setText(cal.get(Calendar.HOUR_OF_DAY) + " 시간 "
				+ cal.get(Calendar.MINUTE) + " 분 " + cal.get(Calendar.SECOND)
				+ " 초");
		// b.setText("" + BtUtil.Bytes2Int(idle));

	}

	private String utilGetHTime(Long drivingTimeSec) {
		RbLog.d(TAG, "utilGetHTime : " + drivingTimeSec);
		int mon, day, hour, min, sec;

		sec = (int) (drivingTimeSec % 60);
		min = (int) (drivingTimeSec / 60);
		hour = (int) (min / 60);
		min = (int) (min % 60);
		day = (int) (hour / 24);
		hour = (int) (hour % 24);
		mon = (int) (day / 31);

		return String.format("%d 개월 %d 일 %d 시간 %d 분 %d 초", mon, day, hour, min,
				sec).toString();

	}

	@Override
	public void onBackPressed() {
		if (mIsListView) {
			finish();
		} else {
			viewSelectTab(mSelectTab, true);
		}
	}

	class MirrorMode extends Animation {
		float cx, cy;

		public void initialize(int width, int height, int parentWidth,
				int parentHeight) {
			super.initialize(width, height, parentWidth, parentHeight);
			cx = width / 2;
			cy = height / 2;
			setDuration(0);
			setFillAfter(true);
			setInterpolator(new LinearInterpolator());
		}

		protected void applyTransformation(float interpolatedTime,
				Transformation t) {
			Camera cam = new Camera();
			cam.rotateY(180 * interpolatedTime);
			Matrix matrix = t.getMatrix();
			cam.getMatrix(matrix);
			matrix.preTranslate(-cx, -cy);
			matrix.postTranslate(cx, cy);
		}
	}

	class OriginMode extends Animation {// ����ġ
		float cx, cy;

		public void initialize(int width, int height, int parentWidth,
				int parentHeight) {
			super.initialize(width, height, parentWidth, parentHeight);
			cx = width / 2;
			cy = height / 2;
			setDuration(0);
			setFillAfter(true);
			setInterpolator(new LinearInterpolator());
		}

		protected void applyTransformation(float interpolatedTime,
				Transformation t) {
			Camera cam = new Camera();
			cam.rotateY(0 * interpolatedTime);
			Matrix matrix = t.getMatrix();
			cam.getMatrix(matrix);
			matrix.preTranslate(-cx, -cy);
			matrix.postTranslate(cx, cy);
		}
	}
}
